import style from "./camera.module.less"
import React, { useState, useEffect } from 'react';
import Select from 'antd/lib/select'; // 假设使用的是Ant Design的Select组件
const {Option} = Select;
const Camera = () => {
    const [cameraList, setCameraList] = useState([]);
    const [selectedCamera, setSelectedCamera] = useState(null);

    useEffect(() => {
        const getCameraList = async () => {
            try {
                const devices = await navigator.mediaDevices.enumerateDevices();
                const cameras = devices.filter(device => device.kind === 'videoinput');
                setCameraList(cameras);
            } catch (error) {
                console.error('Error getting camera list:', error);
            }
        };

        getCameraList();
    }, []);

    const changeCamera = async () => {
        if (!selectedCamera) return;

        try {
            const videoElement = document.getElementById('camera_video');
            const stream = await navigator.mediaDevices.getUserMedia({
                video: {
                    deviceId: { exact: selectedCamera.deviceId }
                }
            });
            videoElement.srcObject = stream;
        } catch (error) {
            console.error('Error changing camera:', error);
        }
    };

    useEffect(() => {
        changeCamera();
    }, [selectedCamera]);

    return (
        <div className={style.container}>
            <div className={style.topBox}>
                <Select
                    placeholder="请选择摄像头"
                    value={selectedCamera ? selectedCamera.label : null}
                    onChange={(value) => {
                        const camera = cameraList.find(camera => camera.label === value);
                        setSelectedCamera(camera);
                    }}
                >
                    {
                        cameraList.map((camera, index) => (
                            <Option key={index} value={camera.label}>
                                {camera.label}
                            </Option>
                        ))
                    }
                </Select>
            </div>

            <video id="camera_video" autoPlay playsInline className={style.video}></video>
        </div>
    );
};

export default Camera;